package meta.assets.presentation;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import meta.api.web.common.util.ApiConst;
import meta.api.web.common.util.ApiUtil;
import meta.assets.conf.AssetsConfParser;
import meta.assets.presentation.form.AssetsForm;
import meta.assets.presentation.form.AssetsResult;
import meta.common.log.CmnLogger;
import meta.common.msg.MessageConst;
import meta.common.util.FileUtil;
import meta.common.util.JsonUtil;
import meta.common.util.StrUtil;

@Controller
@RequestMapping(value="/api")
@Tag(name = "资源管理机能", description = "资源管理机能")
public class AssetsMngController {

    private static final CmnLogger logger = CmnLogger.getLogger(AssetsMngController.class);

    private static final  String FUNC_NM = "资源管理机能";

    private static final String ERROR_MSG_DATA_ERROR= "请求数据错误";
    private static final String ERROR_MSG_GET_ERROR= "获取资源失败";
    private static final String ERROR_MSG_GET_LIST_ERROR= "获取资源列表失败";

    /**
     * 获取指定路径资源目录列表
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/assets/folders")
    @Operation(tags = "获取指定路径资源目录列表", description = "获取指定路径资源目录列表")
    public String folders(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "获取指定路径资源目录列表", null);

        AssetsForm inputdata = JsonUtil.toObj(ApiUtil.readTxtBody(req), AssetsForm.class);

        if (inputdata == null || StrUtil.isEmpty(inputdata.getPath())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        try {
            String path = inputdata.getPath();
            String root = AssetsConfParser.getInstance().getAppWebAssetsRoot();
            boolean prefix = AssetsConfParser.getInstance().getAppWebAssetsPrefix();

            if (!root.endsWith("/")) {
                root = root + "/";
            }
            if (path.startsWith("/")) {
                path = path.substring(1, path.length());
            }
            if (!path.endsWith("/")) {
                path = path + "/";
            }

            // 获取指定路径资源目录列表
            List<String> assets = FileUtil.listSubdir(root, path, prefix);
            if (assets == null) {
                assets = new ArrayList<String>();
            }

            AssetsResult result = new AssetsResult();
            result.setTotal(assets.size());
            result.setList(assets);
            result.setPrefix(prefix);

            ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(result));
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_LIST_ERROR);
        }

        return null;
    }

    /**
     * 获取指定路径资源文件列表
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/assets/files")
    @Operation(tags = "获取指定路径资源文件列表", description = "获取指定路径资源文件列表")
    public String files(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "获取指定路径资源文件列表", null);

        AssetsForm inputdata = JsonUtil.toObj(ApiUtil.readTxtBody(req), AssetsForm.class);

        if (inputdata == null || StrUtil.isEmpty(inputdata.getPath())) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        try {
            String path = inputdata.getPath();
            String root = AssetsConfParser.getInstance().getAppWebAssetsRoot();
            boolean prefix = AssetsConfParser.getInstance().getAppWebAssetsPrefix();

            if (!root.endsWith("/")) {
                root = root + "/";
            }
            if (path.startsWith("/")) {
                path = path.substring(1, path.length());
            }
            if (!path.endsWith("/")) {
                path = path + "/";
            }

            // 获取指定路径资源文件列表
            List<String> assets = FileUtil.listSubfile(root, path, prefix);
            if (assets == null) {
                assets = new ArrayList<String>();
            }

            AssetsResult result = new AssetsResult();
            result.setTotal(assets.size());
            result.setList(assets);
            result.setPrefix(prefix);

            ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(result));
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_LIST_ERROR);
        }

        return null;
    }

    /**
     * 获取资源导航文件
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @GetMapping(value="/assets")
    @Operation(tags = "获取资源导航文件", description = "获取资源导航文件")
    public String assets(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "获取资源导航文件", null);

        try {
            ApiUtil.setJsonResponse(res, Files.readString(Paths.get(ApiConst.WEB_NAVIGATION_FILE)));
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_ERROR);
        }

        return null;
    }
}
